<template>
  <div h-screen relative>
    <uNavbar>
      <nut-input v-model="keyword" :input-style="searchStyle" :custom-style="searchStyle" :placeholder="'搜索商品'"
        @confirm="doSearch(keyword)" :autofocus="isFocus">
        <template #left>
          <div pl-18rpx flex flex-a-c> <nut-icon name="search" /> </div>
        </template>
      </nut-input>
      <div @click="doSearch(keyword)" w-100rpx text-center>搜索</div>
    </uNavbar>
    <div bg-white flex flex-a-c p-16rpx>

    </div>
    <div p-16rpx>
      <div mb-100rpx>
        <div font-bold text-28rpx flex flex-a-c flex-j-sb>
          <div>热门搜索</div>
        </div>
        <div mt-20rpx flex flex-a-c gap-20rpx flex-wrap v-if="hotKeywordList.length">
          <div text-30rpx w-300rpx class="ellipsis" px-24rpx leading-40rpx v-for="(item, index) in hotKeywordList"
            :key="index" @click="doSearch(item)">{{ item }}</div>
        </div>
      </div>

      <div mb-100rpx>
        <div flex flex-a-c flex-j-sb>
          <div font-bold text-28rpx>
            搜索历史
          </div>
          <nut-icon @click="clearHistoryDialog = true" name="del"></nut-icon>
        </div>
        <div mt-20rpx flex flex-a-c gap-20rpx flex-wrap v-if="searchHistories.length">
          <div text-30rpx w-300rpx class="ellipsis" px-24rpx leading-40rpx v-for="(item, index) in searchHistories"
            :key="index" @click="doSearch(item)">{{ item }}</div>
        </div>
      </div>

      <nut-dialog title="提示" content="是否清空搜索历史？" v-model:visible="clearHistoryDialog" @ok="clearHistory" />

    </div>
    <!-- <div absolute bottom-0 left-0 h-100rpx w-100vw bg-slate-50 text-center leading-100rpx text-neutral-500 text-26rpx @tap="oldDelete">清空搜索历史</div> -->
  </div>
</template>

<script setup lang="ts">
import { getHotKeywords } from '@/api/goods';
import { searchStyle } from '@/components/goods-list/common';
import uNavbar from '@/components/navbar/index.vue';
const hotKeywordList = ref<any>([]) //热词
const searchHistories = ref<any>([]) //历史
const keyword = ref<string>('')
const isFocus = ref<boolean>(false);
const clearHistoryDialog = ref<boolean>(false)
const emit = defineEmits(['callback'])

onMounted(() => {
  init();
  isFocus.value = true;
})


// 获取热门搜索关键词
async function fetchHotWords() {
  const res = await getHotKeywords(20)
  let keywords = res.data.result;

  keywords.forEach((item: any) => {
    hotKeywordList.value.push(item);

  });

  keyword.value = hotKeywordList.value[0] || '';
}

// 保存搜索内容到历史记录
function saveSearchword() {
  if (!keyword.value) return false
  uni.getStorage({
    key: 'history_key',
    success: res => {
      var old = JSON.parse(res.data);
      var findIndex = old.indexOf(keyword.value);
      if (findIndex == -1) {
        old.unshift(keyword.value);
      } else {
        old.splice(findIndex, 1);
        old.unshift(keyword.value);
      }
      //最多10个纪录
      old.length > 10 && old.pop();

      uni.setStorage({
        key: 'history_key',
        data: JSON.stringify(old)
      });
      searchHistories.value = old; //更新历史搜索
    },
    fail: e => {
      var old = [keyword.value];
      uni.setStorage({
        key: 'history_key',
        data: JSON.stringify(old)
      });
      searchHistories.value = old; //更新历史搜索
    }
  })
}

// 获取搜索历史
function fetchSearchHistory() {
  uni.getStorage({
    key: 'history_key',
    success: res => {
      var old = JSON.parse(res.data);
      for (let i = 0; i < old.length; i++) {
        searchHistories.value.push(old[i]);
      }
    },
    fail: e => {
    }
  });
}

// 清空搜索历史
function clearHistory() {
  searchHistories.value = []
  uni.removeStorage({
    key: 'history_key'
  })
}
function init() {
  fetchHotWords()
  fetchSearchHistory()
}
// 执行搜索
function doSearch(value: any) {
  let data = value;
  keyword.value = value;
  saveSearchword(); // 保存为历史
  emit('callback', data);
}
</script>

<style scoped>
page,
:root {
  background: #fff
}
</style>
<style scoped lang="scss">
.ellipsis {
  /*width: 100%;*/
  overflow: hidden;
  -webkit-line-clamp: 1;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  white-space: pre-wrap;
}
</style>
